import React from 'react';
import ReactDOM from 'react-dom';
import { connect, Provider } from 'react-redux';
import { createStore, combineReducers } from 'redux';
export { connect };

function dva(){
    const app = {
        _models:[],
        model,
        _router:null,
        router,
        start,
    }
    const initialReducers = {};
    function model(modelConfig){
        const prefixedModel = prefixNamespace(modelConfig); //将modelConfig中的reducers对象的key改成了counter/add和counter/minus
        app._models.push(prefixedModel)
    }
    function router(routerConfig){
        app._router = routerConfig
    }
    function start(root){
        for (const model of app._models) {
            initialReducers[model.namespace] = getReducer(model)
        }
        let rootReducer = combineReducers(initialReducers)
        let store = createStore(rootReducer)
        ReactDOM.render(
            <Provider store = {store}>
                {app._router()}
            </Provider>,document.querySelector(root))
    }
    return app
}
export default dva

// 把model里的reducer 对象转成reducer函数
function getReducer(model){
    let { reducers, state: defaultState } = model;
    let reducer = (state = defaultState,action)=>{
        let reducer = reducers[action.type]
        if(reducer){
            return reducer(state,action)
        }else{
            return state
        }
    }   
    return reducer
}
/**
 * 将reducers中加入命名空间名字
 * @param {*} model 定义的模型
 */
function prefixNamespace(model){
    if(model.reducers){
        model.reducers = prefix(model.reducers, model.namespace);
    }
    return model
}
function prefix(obj, namespace){
    let newObj = {}
    for (const key in obj) {
        newObj[namespace+'/'+key] = obj[key]
    }
    return newObj
}
